package com.ec50n9.server.module.doc

import com.ec50n9.server.module.common.BaseService
import com.ec50n9.server.module.common.renderTo
import com.ec50n9.server.module.ebook.EbookService
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Service
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*

interface DocRepository : CrudRepository<Doc, String>
interface DocContentRepository : CrudRepository<DocContent, String>

@Service
class DocService(docRepository: DocRepository) :
    BaseService<Doc, String>("文档", docRepository)

@Service
class DocContentService(docContentRepository: DocContentRepository) :
    BaseService<DocContent, String>("文档内容", docContentRepository)

@Tag(name = "文档管理")
@RestController
@RequestMapping("/api/docs")
class DocController(
    private val docService: DocService,
    private val ebookService: EbookService,
    private val docContentService: DocContentService
) {

    @Operation(summary = "获取全部")
    @GetMapping
    fun findAll() = docService.findAll().renderTo(DocListRendered::class.java)

    @Operation(summary = "通过id获取")
    @GetMapping("/{id}")
    fun findOne(@PathVariable id: String) = docService.findOne(id).renderTo(DocDetailRendered::class.java)

    @Operation(summary = "新建")
    @PostMapping
    fun newOne(@RequestBody @Validated createForm: DocCreateForm): DocDetailRendered {
        //val ebook = ebookService.findOne(createForm.ebookId!!)
        //val docContent = docContentService.newOne(DocContent(createForm.content!!))
        //val doc = Doc("", docContent, ebook, 0)
        return docService.newOne(createForm.renderTo()).renderTo(DocDetailRendered::class.java)
    }

    @Operation(summary = "更新")
    @PatchMapping("/{id}")
    fun update(@PathVariable id: String, @RequestBody updateForm: DocUpdateForm): DocDetailRendered {
        val doc = docService.findOne(id)
        updateForm.renderTo(doc)
        return docService.update(doc).renderTo(DocDetailRendered::class.java)
    }

    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    fun delete(@PathVariable id: String) {
        val doc = docService.findOne(id)
        docService.delete(doc)
    }
}